package com.boot.framework;

import com.boot.framework.handler.CreateSqlByMethod;
import com.boot.framework.handler.SqlHandlerCache;
import com.boot.framework.handler.TSpringUtils;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.jdbc.core.JdbcTemplate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Slf4j
public class SingleEntityFactoryBean implements FactoryBean<Object> {
    @Setter
    private String tableName;


    @Override
    public Object getObject() throws Exception {

        Object val = Proxy.newProxyInstance(this.getObjectType().getClassLoader(),
                new Class[]{this.getObjectType()}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        CreateSqlByMethod byMethod = SqlHandlerCache.get(method.getName());
                        if (byMethod != null) {
                            String sql = byMethod.sql(tableName, args);
                            JdbcTemplate jdbcTemplate = TSpringUtils.getBean(JdbcTemplate.class);
                            return jdbcTemplate.queryForObject(sql, Integer.class);
                        }
                        return null;
                    }
                });
        return val;
    }


    @Override
    public Class<?> getObjectType() {
        return MapperRepository.class;
    }


}
